package tools

import (
	"context"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"net/url"

	"github.com/axgle/mahonia"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/x/client"
)

const BaseURL = "https://api.weatherapi.com/v1"

type Client struct {
	*client.Client
}
type Options struct {
	BaseURL string
	APIKey  string `json:"api_key" yaml:"APIKey" toml:"APIKey"`
}

type CityResp struct {
	Ip          string `json:"ip"`
	ProCode     string `json:"proCode"`
	City        string `json:"city"`
	Region      string `json:"region"`
	Addr        string `json:"addr"`
	RegionNames string `json:"regionNames"`
	Err         string `json:"err"`
}

func NewClient(opts Options) *Client {
	// apiKeyParameterSetter := client.RequestParam("key", opts.APIKey)

	c := client.New(
		client.Debug,
		client.BaseURL(opts.BaseURL),
		// client.PersistentRequestOptions(apiKeyParameterSetter),
	)

	return &Client{c}
}

func (c *Client) GetCityByIp(ctx context.Context, ip string) string {
	params := client.RequestQuery(url.Values{
		"json": []string{"true"},
		"ip":   []string{ip},
	})

	var response *http.Response
	var respBytes []byte
	var err error

	if response, err = c.Client.JSON(ctx, iris.MethodGet, "", nil, params); err != nil {
		return ""
	}
	// err = c.Client.ReadJSON(ctx, &resp, iris.MethodGet, "", nil, params)
	body := response.Body
	defer body.Close()

	if respBytes, err = ioutil.ReadAll(body); err != nil {
		return ""
	}
	return convertToByte(string(respBytes), "gbk", "utf8").City
}

// 编码转换
func convertToByte(src string, srcCode string, targetCode string) CityResp {
	srcCoder := mahonia.NewDecoder(srcCode)
	srcResult := srcCoder.ConvertString(src)
	tagCoder := mahonia.NewDecoder(targetCode)
	_, cdata, _ := tagCoder.Translate([]byte(srcResult), true)

	var resp CityResp
	_ = json.Unmarshal(cdata, &resp)
	return resp
}
